from django.shortcuts import render
from django.http import HttpResponse
import logging

appid = "wx271d24ea490bbfc0"
appsecret = "581c9142447ad715c014e446c7443858"

logger = logging.getLogger(__name__)

def wxNotify(request):
    msg_sign = request.GET.get('msg_signature', "")
    timestamp = request.GET.get('timestamp', "")
    nonce = request.GET.get('nonce', "")
    from_xml = request.body.decode('utf-8')
    f = open('wxnotify.txt','a+',encoding='utf-8')
    data = f.write(from_xml+'\n')
    # 判断数据格式
    #if from_xml.startswith('<xml>'):
    #     # 解码,使用开放平台配置信息
    #    decrypt_test = WXBizMsgCrypt(open_platform.wx_token, open_platform.encodingAESKey, open_platform.appid)
    #    ret, decryp_xml = decrypt_test.DecryptMsg(from_xml, msg_sign, timestamp, nonce)
    #    if ret == 0:
            # 获取凭证
    #        ticket = decrypt_test.extract_ticket(decryp_xml)

    return HttpResponse("success")

def callBack(request,appid):

    return HttpResponse("success")
    
def getToken(request):
    data = {
        "component_appid": appid,
        "component_appsecret": appsecret,
        "component_verify_ticket": component_verify_ticket
    }
    token_url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'
    # 接口请求
    res = requests.post(token_url, json.dumps(data))
    res_data = json.loads(res.content.decode('utf-8'))
    component_access_token = res_data['component_access_token']
    
    
def preauthcode(request):
    #POST https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=COMPONENT_ACCESS_TOKEN
    return HttpResponse("success")
    
    #授权回调URL
def rewrite_auth_code_handler(self, request, *args, **kwargs):
    auth_code = request.GET.get('auth_code')
    # 获取调用接口凭证 authorizer_access_token
    url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={}".format(component_access_token)
    data = {
        "component_appid": appid,
        "authorization_code": auth_code
    }
    res = requests.post(url, json.dumps(data))
    res_data = json.loads(res.content.decode('utf-8'))
    authorization_info = res_data['authorization_info']
    authorizer_appid = authorization_info['authorizer_appid']
    authorizer_access_token = authorization_info['authorizer_access_token']
    authorizer_refresh_token = authorization_info['authorizer_refresh_token']